import torch
from sklearn.preprocessing import normalize
import numpy as np


def calc_acc(embedding, label):
    """

    :param embedding: [batch_size, 512] torch.tensor
    :param label: [batch_size, 1] torch.tensor but [batch_size // 2. ]
    :return: current data precision(TP / TP + FP) and Recall(TP / TP + FN)
    """
    label = np.array(label.flatten()[0::2])
    embedding = normalize(np.array(embedding), norm='l2', axis=1)
    embedding1 = embedding[0::2]
    embedding2 = embedding[1::2]
    # [B, ]
    dist = np.sum(np.power(embedding1 - embedding2, 2), axis=1, keepdims=False)

    threshold = 1.67
    predict = np.less(dist, threshold)

    TP = np.sum(np.logical_and(predict, label))
    # FP = np.sum(np.logical_and(predict, np.logical_not(label)))
    # FN = np.sum(np.logical_and(np.logical_not(predict), label))
    #
    # precision = 0 if (TP + FP) == 0 else float(TP) / float(TP + FP)
    # recall = 0 if (TP + FN) == 0 else float(TP) / float(TP + FN)
    acc = float(TP) / label.shape[0]
    return acc
